package de.wittekind.bjs.frontend;

import javax.el.ValueExpression;
import javax.faces.application.Application;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import de.wittekind.bundesjugendspiele.exceptions.WrongPasswordException;

@ManagedBean(name = "loginBean")
@ViewScoped
/**
 * @author Fynn Hauptmeier
 */
public class LoginBean {
	private String username;
	private String password;
	private String text;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public String login()
	{
		try {
			getRiegenBean().login(username, password);
		} catch (WrongPasswordException e) {
			text=e.getMessage();
			return "";
		}
		return "pm:stationsauswahl?transition=slide";
	}

	private RiegenBean getRiegenBean() {
		FacesContext context = FacesContext.getCurrentInstance();
		Application app = context.getApplication();
		ValueExpression expression = app.getExpressionFactory()
				.createValueExpression(context.getELContext(),
						String.format("#{%s}", "riegenBean"), Object.class);
		Object bean = expression.getValue(context.getELContext());
		if (bean instanceof RiegenBean) {
			return (RiegenBean) bean;
		}
		return null;
	}
}
